package com.atguigu.spzx.manager.service.Impl;

import com.atguigu.spyx.model.common.ResultCodeEnum;
import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.sys.SysMenu;
import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.sys.SysUser;
import com.atguigu.spyx.model.exception.SpzxException;
import com.atguigu.spyx.model.vo.system.MenuVo;
import com.atguigu.spzx.manager.Interceptor.LoginAuthInterceptor;
import com.atguigu.spzx.manager.mapper.SysMenuMapper;
import com.atguigu.spzx.manager.service.SysMenuService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LT
 * @create 2023-11-06-20:10
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Resource
    SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> findNestdMenus() {
        List<SysMenu> sysMenus = sysMenuMapper.findAll();
        List<SysMenu> parentMenus = sysMenus.stream()
                .filter(sysMenu -> sysMenu.getParentId().longValue() ==0l)
                .collect(Collectors.toList());

        buildMenuTree(sysMenus,parentMenus);

        return parentMenus;
    }



    @Override
    public void deleteById(Long id) {
       Integer count = sysMenuMapper.countChildrenById(id);
        System.out.println(count);
       if (count>0){
           throw new SpzxException(ResultCodeEnum.MENU_DELETE_ERROR,null);
       }
        sysMenuMapper.deleteById(id);
    }

    @Override
    public SysMenu getById(Long id) {
        return sysMenuMapper.getById(id);
    }

    @Override
    public void updateById(SysMenu sysMenu) {
        sysMenuMapper.updateById(sysMenu);
    }

    @Override
    public void save(SysMenu sysMenu) {
        sysMenuMapper.save(sysMenu);
    }

    @Override
    public List<SysMenu> findDynamicMenus() {
        SysUser sysUser = LoginAuthInterceptor.THREAD_LOCAL.get();

        List<SysMenu> menus = sysMenuMapper.findDynamicMenus(sysUser.getId());
        List<SysMenu> parents = menus.stream().filter(menuVos ->menuVos.getParentId().longValue() ==0l)
                .collect(Collectors.toList());
        buildMenuTree(menus,parents);
        return parents;
    }
    private void buildMenuTree(List<SysMenu> all, List<SysMenu> parents) {
        if (CollectionUtils.isEmpty(parents)){
            return;
        }
        parents.forEach(parent->{
            List<SysMenu> children = all.stream().filter(sysMenu -> sysMenu.getParentId().longValue()==
                    parent.getId().longValue()).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(children)){
                parent.setChildren(children);
            }
            buildMenuTree(all,children);
        });

    }
}


